<?php

class ModelState extends CActiveRecordBehavior {
	
	public $configReader = null;
	public $configName;
	public $_config;	
	public $handleField = 'status';
	public $initState = 'ST_NONE';
	protected $_ruleParser;
	
	public function beforeValidate($event) {
		if($this->owner->isNewRecord) {
			$this->setHandleValue($this->initState);
		}
	}
	
	public function getConfig() {
		if(!$this->_config) {
			$config = $this->configReader->read($this->configName);
			if(!isset($config['class'])) $config['class'] = 'ModelStateConfig';
			$this->_config = Yii::createComponent($config);
		}
		return $this->_config;
	}
	
	public function lookup($value = null) {
		$value = $value ? $value : $this->getHandleValue();
		$status = $this->config->status;
		return isset($status[$value]) ? $status[$value] : null;
	}
	
	public function options() {
		return Yii::app()->enum->options($this->config->status);
	}
	
	public function getHandleValue() {
		return $this->owner->{$this->handleField};
	}
	
	protected function setHandleValue($value, $save = false) {
		$this->getOwner()->setAttribute($this->handleField,$value);
		if($save) return $this->owner->save();
		return false;
	}
	
	public function setState($value) {
		if($this->lookup($value)) {
			return $this->setHandleValue($value, true);
		}
		return false;
	}
	
	public function getOperation($name) {
		return $this->config->operations[$name];
	}
	
	public function getOperations() {
		$ruleParser = $this->getRuleParser();
		return $ruleParser->parse();
	}
	
	public function getRuleParser() {
		if(!$this->_ruleParser) {
			$config = $this->config->rules;
			$config['model'] = $this->getOwner();
			$config['stateHandle'] = $this;
			$this->_ruleParser = Yii::createComponent($config);
		}
		return $this->_ruleParser;
	}
	
}

class ModelStateConfig extends Config {
	public function items() {
		return array(
			'status' => array(),
			'operations' => array(),
			'rules' => array(),
		);
	}
}

?>